﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        private static GamePictureBox[] srcPicArr, desPicArr;

        private static Func<IEnumerable<int>, IEnumerable<int>, IEnumerable<Tuple<int, int>>> product = (a, b) =>
        {
            return a.SelectMany((e1) => b.Select((e2) => Tuple.Create(e1, e2)));
        };

        private static Func<int, int, int> genId = (x, y) => (x << 8) + y + 1;

        public MainForm()
        {
            InitializeComponent();

            ImgManager.Prepare();

            GamePictureBox.mainForm = this;

            pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

            reset();
        }

        public bool check()
        {
            return
                Enumerable.All(desPicArr, (e) => e.Id > 0) &&
                Enumerable.All(desPicArr.Zip(desPicArr.Skip(1), (a, b) => b.Id - a.Id), (e) => e > 0);
        }

        public void reset()
        {
            pictureBox.Image = ImgManager.Img;

            srcPanel.BorderStyle = BorderStyle.None;

            desPanel.BorderStyle = BorderStyle.None;

            srcPanel.Controls.Clear();

            desPanel.Controls.Clear();

            IEnumerable<GamePictureBox> srcPicStorage = product(Enumerable.Range(0, 4), Enumerable.Range(0, 4))
                .Select((t) => GamePictureBox.NewInstance(genId(t.Item1, t.Item2), t.Item1, t.Item2));

            Random r = new Random();

            srcPicArr = srcPicStorage.ToArray();

            Enumerable.Range(0, 16).ToList().ForEach((_) => srcPicArr[r.Next(srcPicArr.Length)].swap(srcPicArr[r.Next(srcPicArr.Length)]));

            foreach (var e in srcPicArr) srcPanel.Controls.Add(e);

            IEnumerable<GamePictureBox> desPicStorage = product(Enumerable.Range(0, 4), Enumerable.Range(0, 4))
                .Select((t) => GamePictureBox.NewInstance(genId(t.Item1, t.Item2), t.Item1, t.Item2, true));

            desPicArr = desPicStorage.ToArray();

            foreach (var e in desPicArr) desPanel.Controls.Add(e);
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void NewGame_Click(object sender, EventArgs ent)
        {
            reset();
        }
    }
}
